<script lang="ts" setup>
import { computed, ref } from 'vue';
import { useUserStore } from '@/store/user';
import { VisitorLogin } from '@/types/visitorLogin';
import { useRouter } from '@/router';
import { onLoad } from '@dcloudio/uni-app';
import * as CsService from '@/api/cs';
import { GET_BASE_CONFIG } from '@/http/env';

const router = useRouter();

const userStore = useUserStore();
const LoginParams = ref<VisitorLogin>({
  kefu_id: '',
  ent_id: GET_BASE_CONFIG().ENT_ID,
  language: 'zh-CN',
  visitor_id: ''
});
// 创建一个计算属性
const loadCsUrl = computed(() => {
  let params = objectToQueryStringManual(LoginParams.value);
  return GET_BASE_CONFIG().CS_BASE_URL + '/chatIndex?' + params;
});

const TempRes = ref();

onLoad(async (options) => {
  if (options!.id != undefined && options!.type != undefined) {
    const TempResp = await CsService.languageTemplate({
      id: options!.id,
      type: options!.type
    });
    TempRes.value = TempResp.data.template;
  }

  // 读取用户信息
  LoginParams.value.visitor_id = LoginParams.value.ent_id + '|' + userStore.user.id;
  uni.request({
    url: GET_BASE_CONFIG().CS_BASE_URL + '/visitor_login', //仅为示例，并非真实接口地址。
    method: 'POST',
    data: {
      visitor_id: LoginParams.value.visitor_id,
      language: 'zh-CN',
      ent_id: LoginParams.value.ent_id
    },
    header: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    },
    success: (res: any) => {
      LoginParams.value.kefu_id = res.data.result.to_id;
      if (options!.id != undefined && options!.type != undefined) {
        // 发送消息
        uni.request({
          url: GET_BASE_CONFIG().CS_BASE_URL + '/2/message?lang=',
          method: 'POST',
          data: {
            content: TempRes.value,
            from_id: LoginParams.value.visitor_id,
            to_id: LoginParams.value.kefu_id,
            is_autoreply: 'yes'
          },
          header: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
          }
        });
      }
    }
  });
});

function objectToQueryStringManual(obj: any) {
  return Object.keys(obj)
    .map((key) => {
      return encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]);
    })
    .join('&');
}
</script>

<template>
  <view v-if="LoginParams.kefu_id">
    <web-view :src="loadCsUrl"></web-view>
  </view>
</template>
